package com.alpha.realife.utils;

import sun.net.www.protocol.ftp.FtpURLConnection;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @version V1.0
 * @author: Albert
 * @date: 2020/7/1 18:49
 * @description:
 */
@SuppressWarnings("all")
public class WeiboDownLoads {

    private WeiboDownLoads() {
    }

    public static Map<String, Object> download(String url, String destFile) {

        //封装下载报告
        Map<String, Object> resultMap = new HashMap<>();
        long startTime = System.currentTimeMillis();

        FtpURLConnection ftpURLConnection = null;
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL weibo = new URL(url);
            urlConnection = ((HttpURLConnection) weibo.openConnection());

            //获取连接
            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream(destFile);

            byte[] carBuffer = new byte[102400];
            int len;
            while ((len = is.read(carBuffer)) != -1) {
                fos.write(carBuffer, 0, len);
            }

            System.out.println("下载完成...");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ResourceCloseUtils.close(is, fos);
            ResourceCloseUtils.disconnect(urlConnection);
        }

        long endTime = System.currentTimeMillis();
        long downLoadTime = endTime - startTime;
        //
        File dest = new File(destFile);
        long fileSize = dest.length();
        //
        double avgSpeed = (fileSize / 1024.0 / 1024.0) / (downLoadTime / 1000.0);
        //
        resultMap.put("下载过程耗时(单位:毫秒)", downLoadTime);
        resultMap.put("平均下载速度(单位:M/s)", avgSpeed);

        return resultMap;
    }
}

